import React, {useEffect} from "react";
import {
  Box,
  Button,
  Checkbox,
  Container,
  CssBaseline,
  FormControlLabel, Grid, Link,
  Paper,
  TextField,
  Typography
} from "@mui/material";
import axios from "axios";
import {useNavigate} from "react-router-dom";

function Copyright(props) {
  return (
    <Typography variant="body2" color="text.secondary" align="center" {...props}>
      {'Copyright © '}
      <Link color="inherit" href="https://chat.cyril.tech/">
        Anonymous Chat Room
      </Link>{' '}
      {new Date().getFullYear()}
      {'.'}
    </Typography>
  );
}

export default function SignUp(){

  const getCSRF = () => {
    fetch("/api/csrf", {
      credentials: "same-origin",
    })
      .then((res) => {
        const csrfToken = res.headers.get("X-CSRFToken");
        axios.defaults.headers.common['X-CSRFToken'] = csrfToken
      })
      .catch((err) => {
        console.log(err);
      });
  }
  const getSession = () => {
    getCSRF()
    axios.get("/api/session")
      .then((res) => res.data)
      .then((data) => {
        console.log(data);
        if (data.isAuthenticated) {
          navigate('/home')
        }
      })
      .catch((err) => {
        console.log(err);
      });
  }

  useEffect(() => {
    getSession()
  }, [])
  const navigate = useNavigate()

  function handleSubmit(event){
    event.preventDefault();
    const data = new FormData(event.currentTarget);
    const username = data.get('username')
    const password = data.get('password')
    const password2 = data.get('password2')
    if(typeof password === undefined || password == null || password === ''){
      window.alert("密码不能为空！")
      return;
    }
    if(password !== password2){
      window.alert("两次密码不一致！")
      console.log({'pswd':password, 'pswd2': password2})
      return;
    }
    axios.post('/api/signup', {
      'username': username,
      'password': password
    }).then(res => {
      if(res.status >= 200 &&res.status <= 299){
        window.alert('注册成功！跳转登陆界面')
        navigate('/')
      } else {
        window.alert(res.data.detail)
      }
    }).catch(err =>{
      console.log(err)
      window.alert(err.response.data.detail)
    })
  }
  return(
    <Container component="main" maxWidth="xs">
      <CssBaseline />
      <Paper elevation={3}>
        <Box sx={{
          margin: '32px 16px',
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
        }}>
          <Typography component="h1" variant="h5">
            Sign Up
          </Typography>
          <Box component="form" onSubmit={handleSubmit} noValidate sx={{ mt: 1 }}>
            <TextField
              margin="normal"
              required
              fullWidth
              id="username"
              label="用户名"
              name="username"
              autoComplete="username"
              autoFocus
              variant="outlined"
            />
            <TextField
              margin="normal"
              required
              fullWidth
              name="password"
              label="密码"
              type="password"
              id="password"
              autoComplete="current-password"
              variant="outlined"
            />
            <TextField
              margin="normal"
              required
              fullWidth
              name="password2"
              label="再次确认密码"
              type="password"
              id="password2"
              autoComplete="current-password"
              variant="outlined"
            />
            <Button
              type="submit"
              fullWidth
              variant="contained"
              sx={{ mt: 3, mb: 2 }}
            >
              注册
            </Button>
          </Box>
        </Box>
      </Paper>
      <Copyright sx={{ mt: 8, mb: 4 }} />
    </Container>
  )
}